<template lang='pug'>
  section.bg
    van-nav-bar(
      :title="username.substr(0, 8) + '的代言'"
      left-arrow
      @click-left="$back()"
      :fixed="true"
      @click-right="shareShow = true"
      :style="{background: `${navColor}!important`}"
      )
      van-icon(name="home" slot="left" size="1.5rem" color="#fff" v-if="referrerId")
      van-icon(name="share" slot="right" size="1.5rem" color="#fff")
    header(@click="headClick")
      .no-data(v-show="(!images || !images.length) && !video")
        van-button(size="small" v-show="!referrerUser") 上传封面
      vanswipe(:images="images" :showImagePreview="false" v-show="images && images.length")
      video(
        :src="video" 
        controls
        v-show="video"
        )
      .avatar(:style='{backgroundImage: `url(${headImageUrl})`}')
    van-list(
      v-model="isLoading"
      :finished="finished"
      @load="onLoad"
      :offset="offset"
      )
      card(
        v-bind="cardData(commodity)" 
        v-for="commodity in commoditys" 
        :key="commodity.id" 
        @click="$router.push('/detail/' + commodity.id)")
        cardRight(:commodity="commodity")
      //- .card(v-for="commodity in commoditys" :key="commodity.id")
      //-   .background-img.bg-img-ratio(
      //-     :style='{backgroundImage: `url(${commodity.mainImage || ""})`}'
      //-     )
      //-   .amount ¥30.0
      //-     .sell-count.color-l 已售出0件
        
      //-   .card-title {{commodity.name}}
      //-   .card-desc.color-l {{commodity.subtitle}}
    //- footer
    //-   van-button(size="large" type="danger" @click="shareShow = true") 分享
    share(v-model="shareShow")
    media(v-model="editCoverShow" @complete="editCover")
    
</template>

<script type='text/ecmascript-6'>
  import share from '~/components/share'
  import media from '~/components/media'
  import vanswipe from '~/components/vanswipe'
  import { pageSize, offset } from '~/config/search'
  import card from '~/components/card'
  import cardRight from '~/components/card-right'

  export default {
    components: {
      share,
      media,
      vanswipe,
      card,
      cardRight,
    },
    data() {
      return {
        isLoading: false,
        finished: false,
        shareShow: false,
        editCoverShow: false,
        pageNum: 1,
        commoditys: [],
        offset,
        actions: [
          {name: '图片'},
          {name: '视频'},
        ],
        screenWidth: 0,
        scroll: null,
        scrollView: null,
        scrollTop: 0,
        referrerUser: null,
      }
    },
    computed: {
      user() {
        return this.$store.state.authUser || {}
      },
      userId() {
        if (!this.user ||!this.user.user) return ''
        return this.user.user.id
      },
      referrerId() {
        return this.$route.query.referrerId
      },
      username() {
        const user = this.referrerId ? this.referrerUser : this.user
        if (!user ||!user.userWx) return ''
        return user.userWx.nickname || ''
      },
      headImageUrl() {
        const user = this.referrerId ? this.referrerUser : this.user
        if (!user ||!user.userWx) return ''
        return user.userWx.headImageUrl || ''
      },
      shopImg() {
        const user = this.referrerId ? this.referrerUser : this.user
        if (!user ||!user.user) return []
        return JSON.parse(user.user.shopImg || '[]')
      },
      video() {
        const item = this.shopImg.find(item => item.type === 2) || {}
        return item.linkUrl || ''
      },
      images() {
        const items = this.shopImg.filter(item => item.type === 1)
        return items.map(item => item.linkUrl)
      },
      navColor() {
        const total = 250
        const num = Math.min(1, this.scrollTop / total)
        return `rgba(232, 25, 15, ${num})`
      },
    },
    beforeMount() {
      this.screenWidth = window.screen.width

      this.scrollView = this.getScrollview()
      this.scrollView.addEventListener('scroll', this.scroll = () => {
        let offsetTop = window.pageYOffset
        if (this.scrollView !== window) offsetTop = this.scrollView.scrollTop
        this.scrollTop = offsetTop
      })

      this.share()
      this.getReferrerUser()
    },
    methods: {
      headClick() {
        if (this.referrerUser) return
        this.editCoverShow = true
      },
      async getReferrerUser() {
        if(!this.referrerId) return
        const resp = await this.$post('/api/platform/user/findUserInfoByUserId', { userId: this.referrerId })
        if (resp && resp.data) this.referrerUser = resp.data
      },
      share() {
        let config = {
          title: this.username + '为雪顿代言',
          desc: '雪顿是甘南乳都有信仰的企业。因为信仰，所以纯净，高原净土的馈赠，请和我一起来代言',
          imgUrl: this.headImageUrl
        }
        this.wxShare(config, this.userId)
      },
      cardData(commodity) {
        const {mainImage: url, name: title, subtitle: desc, price, soldStock: sellCount} = commodity
        const data = { url, title, desc, price, sellCount }
        return data
      },
      async onLoad() {
        this.isLoading = true
        const resp = await this.$post('/api/platform/product/productPage', {pageSize, pageNum: this.pageNum})
        this.isLoading = false
        const _list = resp.data.list || []
        if (_list.length < pageSize) this.finished = true
        this.commoditys = [...this.commoditys, ..._list]
        this.pageNum++
      },
      editCover(data) {
        this.$post('/api/platform/user/update', {shopImg: JSON.stringify(data), id: this.userId})
          .then(resp => {
            if (resp.data) {
              const user = Object.assign({}, this.user || {}, {user: resp.data})
              this.$store.commit('SET_USER', user)
            } else {
              this.$toast('操作失败')
            }
          })
          .catch(() => { this.$toast('操作失败') })
          .finally(() => { this.editCoverShow = false })
        // /api/platform/user/update
      },
      selectEditCover() {},
      getScrollview(el) {
        let currentNode = el
        while (currentNode && currentNode.tagName !== 'HTML' && currentNode.tagName !== 'BODY' && currentNode.nodeType === 1) {
          let overflowY = document.defaultView.getComputedStyle(currentNode).overflowY
          if (overflowY === 'scroll' || overflowY === 'auto') {
            return currentNode
          }
          currentNode = currentNode.parentNode
        }
        return window
      }
    },
    beforeDestroy() {
      this.scrollView.removeEventListener('scroll', this.scroll)
    },
  }
</script>

<style lang='stylus' rel='stylesheet/stylus' scoped>

@import '~assets/stylus/variable.styl'
 
section
  min-height 100vh
  padding-bottom 5rem

header
  position relative
  .no-data
    height 250px
    background-image linear-gradient(to bottom, rgba(232, 25, 15, 1), rgba(244, 82, 5, 1))
    display flex
    align-items center
    justify-content center
    .van-button
      background-color transparent
      color $color-white
      opacity 0.7
    // &::after
    //   color #ffffff
    //   content '上传封面'
    //   border 1px solid currentColor
    //   padding 5px 10px
    //   border-radius 5px
  .avatar
    border 2px solid #fff
    width 5rem
    height 5rem
    position absolute
    bottom -2rem
    left 1rem
    right 1rem
    
  video
    width 100%
  .van-custom-indicator
    position absolute
    bottom 1rem
    right 1rem
    color $color-white
    background-color rgba(0,0,0,.5)
    width 3.5rem
    height 3.5rem
    border-radius 50%
    text-align center
    line-height 3.5rem
    letter-spacing 2px

.van-list
  margin-top 3rem
//   padding 1rem 1rem
.btn-detail, .btn-buy
  margin-left 1rem
footer
  position fixed
  bottom 0
  width 100%
  box-sizing border-box
</style>
